"use client";

import { type ReactNode, createContext, useRef, useContext } from "react";
import { useStoreWithEqualityFn } from "zustand/traditional";
import {
  createContentStore,
  ResumesContentStore,
} from "../stores/content-store";

export type StoreApi = ReturnType<typeof createContentStore>;

export const StoreContext = createContext<StoreApi | undefined>(undefined);

export interface ContentStoreProviderProps {
  children: ReactNode;
  content: ResumesContent;
}

export const ContentStoreProvider = ({
  children,
  content,
}: ContentStoreProviderProps) => {
  const storeRef = useRef<StoreApi>();
  if (!storeRef.current) {
    storeRef.current = createContentStore({ ...content });
  }

  return (
    <StoreContext.Provider value={storeRef.current}>
      {children}
    </StoreContext.Provider>
  );
};

export const useContentStore = <T,>(
  selector: (store: ResumesContentStore) => T,
  equalityFn?: (a: T, b: T) => boolean
): T => {
  const contentStoreContext = useContext(StoreContext);
  if (!contentStoreContext) {
    throw new Error(`useCounterStore must be used within CounterStoreProvider`);
  }

  return useStoreWithEqualityFn(contentStoreContext, selector, equalityFn);
};
